package com.cxyd.common.aspect;

import com.cxyd.common.utils.HttpContextUtils;
import com.cxyd.modules.log.entity.SysLogApiEntity;
import com.cxyd.modules.log.service.SysLogApiService;
import com.cxyd.common.utils.IpUtils;
import com.cxyd.common.utils.JsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class LogApiAspect {
    @Autowired
    private SysLogApiService sysLogApiService;

    //切面链接点放到注解上
    @Pointcut("@annotation(com.cxyd.common.annotation.LogApiOperation)")
    public void logPointCut() {

    }

    @Before("logPointCut()")
    public void logRecord(JoinPoint point){
        saveLog(point);
    }

    private void saveLog(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SysLogApiEntity apiLog = new SysLogApiEntity();

        apiLog.setApiName(signature.getName());
        //请求相关信息
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        apiLog.setIp(IpUtils.getIpAddr(request));
        apiLog.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
        apiLog.setApiUri(request.getRequestURI());
        apiLog.setApiMethod(request.getMethod());

        //请求参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = JsonUtils.toJsonString(args[0]);
            apiLog.setApiParams(params);
        } catch (Exception e) {

        }

        //保存到数据库
        sysLogApiService.save(apiLog);
    }
}
